from abc import ABCMeta, abstractmethod

from utils.base.WindowHelper import *
from utils.base.WindowUtils import *
from utils.base.TkinterEvent import *

class BaseWindow(object):
    __meta_class__ = ABCMeta

    def __init__(self, master=None, *args, **kwargs):
        self.master = master
        self.root: tk.Tk | tk.Toplevel | None = None
        self.frame: tk.Frame | None = None
        self.kwargs = {
            'cls': tk.Tk,
            'width': ix2px(40),
            'height': iy2px(40),
            'icon': None,
            'title': '',
            'is_auto_center': True
        }
        self.config(self.kwargs)
        self.width = self.kwargs['width']
        self.height = self.kwargs['height']
        # 自动居中于父布局
        if master is not None and self.kwargs['is_auto_center']:
            center = master.center
            self.kwargs['x'] = center[0] - self.width / 2
            self.kwargs['y'] = center[1] - self.height / 2
        self.x = 0
        self.y = 0
        self.center = (0, 0)
        self.init_root()
        self.root.update()
        self.view(self.frame)
        self.created()
        pass

    @abstractmethod
    def config(self, kwargs):
        """
        cls、width、height、title、icon
        """
        pass

    def init_root(self):
        k: dict = self.kwargs
        m = self.master
        if m is not None:
            m = m.root
        root = k['cls'](m)
        self.width, self.height, self.frame = init_root(root, **k)
        self.root = root
        event_bind(self.root, event_intent(EventType.Configure), self.__winfo_changed)

    def add_child(self, child):
        if isinstance(child, BaseWindow):
            child = child.root
        set_parent_tkinter(child, self.root)

    @abstractmethod
    def view(self, frame: tk.Frame):
        pass

    def created(self):
        pass

    def start(self):
        self.root.mainloop()

    def stop(self):
        self.root.destroy()

    def size_hide(self):
        self.root.state('withdrawn')

    def size_maximize(self):
        self.root.state('zoomed')

    def size_normal(self):
        self.root.state('normal')

    def size_minimize(self):
        self.root.state('icon')

    def __winfo_changed(self, e):
        self.width = self.root.winfo_width()
        self.height = self.root.winfo_height()
        self.x = self.root.winfo_x()
        self.y = self.root.winfo_y()
        self.center = int(self.x + self.width / 2), int(self.y + self.height / 2)
        self.winfo_changed(e)
        pass

    def winfo_changed(self, e):
        pass

    def get_width(self):
        return self.width
    def get_height(self):
        return self.height
